<template>
  <div class="create-post-page">
    <h4>{{isEditMode ? '编辑文章' : '新建文章'}}</h4>
    <Uploader
      action='/upload'
      class="d-flex align-items-center justify-content-center bg-light text-secondary w-100 my-4"
      style="height: 200px; cursor: pointer;"
      :beforeUpload="UploadCheck"
      @file-uploaded="handleFileUpload"
      :uploaded="uploadedData"
    >
      <h4>点击上传图片</h4>
      <template #loading>
        <div class="d-flex">
          <div class="spinner-border text-secondary" role="status">
            <span class="sr-only">Loading...</span>
          </div>
          <h4>正在上传</h4>
        </div>
      </template>
      <template #uploaded="dataProps">
        <img :src="dataProps.uploadedData.data.url" alt="" style="width: 100%; height: 100%;object-fill: cover;">
      </template>
    </Uploader>
    <validate-form @form-submit="onSubmitForm">
      <div class="mb-3">
        <label class="form-label">文章标题：</label>
        <validate-input :rules="titleRules" v-model="titleVal" placeholder="请输入文章标题"></validate-input>
      </div>
      <div class="mb-3">
        <label class="form-label">文章详情：</label>
        <validate-input
          :rules="contentRules"
          v-model="contentVal"
          placeholder="请输入文章详情"
          type="text"
          tag='textarea'
          rows='10'
        >
        </validate-input>
      </div>
      <template #submit>
        <button class="btn btn-primary btn-large">{{isEditMode ? '更新文章' : '发表文章'}}</button>
      </template>
    </validate-form>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, onMounted } from 'vue'
import { useStore } from 'vuex'
import { useRouter, useRoute } from 'vue-router'
import { GlobalDataProps, PostProps, ResponseType, PostResponseType } from './../store'
import ValidateInput, { RulesProp } from './../components/ValidateInput.vue'
import ValidateForm from './../components/ValidateForm.vue'
import Uploader from './../components/Uploader.vue'
import { beforeUploadCheck } from './../helper'
import CreateMessage from './../components/CreateMessage'
export default defineComponent({
  name: 'create-post',
  components: {
    ValidateInput,
    ValidateForm,
    Uploader
  },
  setup () {
    const store = useStore<GlobalDataProps>()
    const router = useRouter()
    const route = useRoute()
    const isEditMode = !!route.query.id
    const uploadedData = ref()
    const titleRules: RulesProp = [
      { type: 'required', message: '文章标题不能为空' }
    ]
    const contentRules: RulesProp = [
      { type: 'required', message: '文章详情不能为空' }
    ]
    const titleVal = ref('')
    const contentVal = ref('')
    let imageId = ''
    const onSubmitForm = (result: boolean) => {
      if (result) {
        const { column, _id } = store.state.user
        if (column) {
          const newPost: PostProps = {
            title: titleVal.value,
            content: contentVal.value,
            column,
            author: _id
          }
          if (imageId) {
            newPost.image = imageId
          }
          const actionName = isEditMode ? 'updatePost' : 'createPosts'
          const payloadData = isEditMode ? {
            id: route.query.id,
            payload: newPost
          } : newPost
          store.dispatch(actionName, payloadData).then(() => {
            CreateMessage('发表成功2秒后跳转', 'success', 2000)
            setTimeout(() => {
              router.push({ name: 'column', params: { id: column } })
            }, 2000)
          })
        }
      }
    }
    const handleFileUpload = (rawData: ResponseType) => {
      if (rawData.data._id) {
        imageId = rawData.data._id
      }
    }
    const UploadCheck = (file: File) => {
      const result = beforeUploadCheck(file, { format: ['image/jpg', 'image/jpeg', 'image/png'], size: 1 })
      const { passed, err } = result
      if (err === 'format') {
        CreateMessage('图片格式只能为JPG，JPEG，PNG', 'error', 2000)
      }
      if (err === 'size') {
        CreateMessage('图片大小不能超过1M', 'error', 2000)
      }
      return passed
    }
    onMounted(() => {
      const id = route.query.id
      if (!id) {
        return
      }
      store.dispatch('fetchPost', id).then((rawData: PostResponseType) => {
        const currentPost = rawData.data
        if (currentPost.image) {
          uploadedData.value = { data: currentPost.image }
        }
        titleVal.value = currentPost.title
        contentVal.value = currentPost.content || ''
      })
    })
    return {
      titleRules,
      contentRules,
      titleVal,
      contentVal,
      onSubmitForm,
      UploadCheck,
      handleFileUpload,
      isEditMode,
      uploadedData
    }
  }
})
</script>
